<template>
  <div class="gattstic-yell" v-loading="state.loading" element-loading-background="#909399">
    <div style="display: flex;">
      <div class="menu-name"></div>
      <div style="display: flex; justify-content: space-between; flex: 1;">
        <div v-for="item in 12" style="flex: 1; text-align: left;">
          {{ props.classes === "morning" ? item + 7 : item < 5 ? item + 19 : item - 5 }}:00 </div>
        </div>
      </div>
      <div v-for="item in state.menuTimeList" :key="item.jitai_uid" style="display: flex;">
        <div class="menu-name bg">
          {{ item.jitai_name }}
        </div>
        <div class="menu-item" style="flex: 1;">
          <template v-for="(itemsB, itemIndex) in planBlock[item.jitai_code]" :key="`${itemIndex}-${itemsB.doneCount}`">
            <div class="item-time-plan" v-if="itemsB.left >= 0"
              :style="{ width: `${itemsB.width}%`, left: `${itemsB.left}%` }"
              @mouseenter="showTooltip($event, state.dataList[item.jitai_code][itemIndex], itemsB)"
              @mousemove="showTooltip($event)" @mouseleave="state.tooltip.show = false">
              <div class="item-plan-done" :style="{ width: `${itemsB.done}%` }"></div>
            </div>
          </template>
        </div>
      </div>
      <!-- 信息框 -->
      <div class="plan-info" v-show="state.tooltip.show"
        :style="{ left: `${state.tooltip.x}px`, top: `${state.tooltip.y}px` }">
        <div class="plan">设备类型: {{ props.checkMenu?.jitai_xinghao }}</div>
        <div class="plan">机台号: {{ state.tooltip.planData[0] }}</div>
        <div class="plan">时间: {{ state.tooltip.planData[8] }}</div>
        <div class="plan">订单号: {{ state.tooltip.planData[2] }}</div>
        <div class="plan">卡号: {{ state.tooltip.planData[4] }}</div>
        <div class="plan">客户: {{ state.tooltip.planData[1] }}</div>
        <div class="plan">产品信息: {{ state.tooltip.planData[3] }}</div>
        <div class="plan">米数: {{ state.tooltip.planData[7] }}</div>
        <div class="done">实际产量: {{ state.tooltip.process.doneCount }}</div>
      </div>
    </div>
</template>
<script setup lang="ts">
// import { useBaseDataStore } from '@/store';
import { computed, ref, onMounted } from 'vue';
import { getDapingList, getDataSyncexCL, InDeviceSync, InHESData } from "@/api/timing";
import moment from "moment";
/** api */
// const baseDataStore = useBaseDataStore();
/** api */
interface Props {
  menuList?: Array<InDeviceSync>,
  checkMenu?: InDeviceSync;
  checkTime?: string;
  /** 班次 */
  classes: "morning" | "evening";
}
// 组件传参
const props = withDefaults(defineProps<Props>(), {});
const emits = defineEmits(['callback']);
/** 进度条 */
interface InProcess {
  /** 是否显示 */
  show: boolean;
  /** 左边距离 */
  left: number;
  /** 宽度 */
  width: number;
  /** 完成率 */
  done: number;
  /** 完成数 */
  doneCount: number;
}
/** 数据 */
interface State {
  /** 数据状态 */
  loading: boolean;
  listLength: number;
  dataList: {
    [key: string]: string[][]
  };
  menuTimeList: InDeviceSync[];
  // leftMenuList: any[];
  /** 实际产量数据 */
  chanliang: InHESData[];
  /** 显示框位置 */
  tooltip: {
    show: boolean;
    x: number;
    y: number;
    planData: string[];
    process: InProcess;
  }
}
let state = ref<State>({
  loading: false,
  listLength: 900,
  dataList: {},
  menuTimeList: [],
  // leftMenuList: [],
  chanliang: [],
  tooltip: {
    show: false,
    x: 0,
    y: 0,
    planData: [],
    process: {
      show: true,
      left: 0,
      width: 0,
      done: 0,
      doneCount: 0
    }
  }
});
onMounted(() => {
  state.value.menuTimeList = props.menuList || [];
  state.value.menuTimeList.map(item => {
    item.jitai_name = item.jitai_name.replace(/#/g, "");
    return item;
  })
  state.value.menuTimeList?.sort((a, b) => b.jitai_name.localeCompare(a.jitai_name));
  getDapingTableList();
})
//http://192.168.100.12:8097/api/v1/daping/device?day=2024-05-16&factory_id=1
/** 获取计划及实际生产数据 */
async function getDapingTableList(device_id?: string) {
  state.value.loading = true;
  const res01 = await getDataSyncexCL(`${props.checkTime} 00:00`, `${props.checkTime} 23:59`).catch(() => undefined)
  state.value.chanliang = res01?.data.DATA ?? [];

  const res02 = await getDapingList({
    day: props.checkTime,//'2024-05-29',
    factory_id: '1'
  }).catch(() => undefined)
  state.value.dataList = res02?.data?.data[props.checkMenu?.jitai_xinghao || ''] ?? {};
  state.value.loading = false;
}
defineExpose({
  getDapingTableList
})
/** 进度条信息面板显示 */
function showTooltip(e: { clientX: number; clientY: number; layerX: number; layerY: number; screenX: number; screenY: number; pageX: number; pageY: number; }, data?: string[], process?: InProcess) {
  // console.log(2222, e);
  state.value.tooltip.show = true;
  // state.value.tooltip.x = (e.pageX - (process && process.left > 70 ? 300 : 0)) * (1/window.devicePixelRatio);
  // state.value.tooltip.y = (e.pageY - 120) * (1/window.devicePixelRatio);
  state.value.tooltip.x = (e.clientX - (process && process.left > 70 ? 300 : 0)) * (window.devicePixelRatio || 1) - 50;
  state.value.tooltip.y = (e.clientY - e.layerY - 200);
  if (data) {
    state.value.tooltip.planData = data;
  }
  if (process) {
    state.value.tooltip.process = process;
  }
}
/** 计算属性 */
/** 动态计算计划任务进度 */
const planBlock = computed(() => {
  /** 当前小时 */
  const currentHour = moment().hour();
  const body: { [key: string]: InProcess[] } = {};
  for (const key in state.value.dataList) {
    if (Object.prototype.hasOwnProperty.call(state.value.dataList, key)) {
      const element = state.value.dataList[key];
      body[key] = [];
      element.forEach(item => {
        if (item[8] && item[8].includes("~")) {
          const [startTime, endTime] = item[8].split("~");
          /** 实际产量 */
          const doneNum = state.value.chanliang.filter(val => val.sWorkingProcedureName === item[5] && val.sCardNo == item[4] && val.sEquipmentModelName == props.checkMenu?.jitai_xinghao).reduce((prv, cur) => {
            return prv += cur.nTrackQty ?? 0;//cur.nZHTrackQty ?? 0;//
          }, 0);
          /** 早晚班节点时间 */
          let nodeTime = moment(`${props.checkTime} ${props.classes === "morning" ? '08:00:00' : '20:00:00'}`);
          if (currentHour <= 8) {
            nodeTime = moment(`${props.checkTime} 20:00:00`).subtract(1, "days");
          }
          const data: InProcess = {
            show: true,
            left: parseFloat((moment(startTime).diff(nodeTime) / 60000 * 0.139).toFixed(2)),
            width: parseFloat((moment(endTime).diff(moment(startTime)) / 60000 * 0.139).toFixed(2)),
            done: doneNum * 100 / parseInt(item[7]),
            doneCount: doneNum
          };
          body[key].push(data);
          // console.log(11111, key, item, doneNum, body);
        }
      })
    }
  }
  return body;
})
</script>
<style lang="scss" scoped>
.gattstic-yell {
  // height: 789px; //736px;

  .menu-name {
    padding: 2px 0;
    padding-left: 44px;
    width: 174px;
    box-sizing: border-box;
    margin-right: 4px;

    &.bg {
      background-image: url("@/assets/imgs/ganttastic/menu-bg.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
  }

  .menu-item {
    box-sizing: border-box;
    margin: 2px 0;
    background-color: #454545;//#002d58;
    position: relative;
    overflow: hidden;

    .item-time-plan {
      position: absolute;
      height: 100%;
      background-color: #E8D945;//var(--el-color-primary);
      top: 0;
      cursor: pointer;
      overflow: hidden;
      border-radius: 2px;

      .item-plan-done {
        height: 100%;
        background-color: #AAE65A;//var(--el-color-success);
      }
    }
  }

  .plan-info {
    position: fixed;
    top: 0;
    left: 0;
    background-color: var(--el-text-color-primary);//#00223B;
    padding: 12px;
    border-radius: 6px;
    width: 320px;

    .plan {
      color: #E8D945;//var(--el-color-primary);
    }

    .done {
      color: #AAE65A;//var(--el-color-success);
    }
  }
}
</style>